import React, { Component } from 'react'
import {
    StyleSheet,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    RefreshControl,
    TouchableWithoutFeedback,
    Platform,
    Text
} from 'react-native';
// import Icon from 'react-native-vector-icons/FontAwesome'

const Dimensions = require('Dimensions');
const { width } = Dimensions.get('window');

// common 
// import BottomBarLimit from '../../common/BottomBarLimit'
import Loading from '../../common/Loading'

import RecommendTea from '../../component/RecommendTea'
import NavigatorBar from '../../common/NavigationBar';
import { searchTeacher } from '../../api/home';

const cacheData = {
    nextPage: 1,
    total: 0,
    items: []
}
export default class TeacherSearchpage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            TeacherList: [],
            SORTBYTIME: 1,
            USERID: global.ECourseConstant.userInfo.uuid,
            NAME: '',
            isRefreshing: false,
            isLoading: false,
            TeacherMore: false,
            loading: false
        };
    }

    // 渲染按钮 返回按钮
    renderLeftButton(image) {
        return <TouchableWithoutFeedback onPress={() => {
            this.props.navigation.goBack();
        }}>
            <View
                style={[global.CommonStyleSheet.NavLeftButton]}
            >
                <Image
                    style={{ width: 34, height: 34 }}
                    source={image} />
            </View>
        </TouchableWithoutFeedback>
    }

    componentDidMount() {
        this._fetchData()
    }

    _fetchData() {

        var data = {
            sendData: {
                "USERID": this.state.USERID,
                "SORTBYTIME": this.state.SORTBYTIME,
                "NAME": this.state.NAME,
            },
            page: cacheData.nextPage,
            rows: 10
        };
        this.setState({
            isLoading: true
        });

        searchTeacher(data).then(res => {
            global.log(res, '-----res');
            cacheData.items = this.state.TeacherList.concat(res.LIST);
            cacheData.total = res.PAGINATION.TOTAL;
            var data = [...cacheData.items]
            this.setState({
                TeacherList: data,
                isLoading: false,
                isRefreshing: false
            })

        })
    }

    render() {
        return (
            <View style={styles.appContainer}>
                <NavigatorBar
                    title={'教师列表'}
                    style={styles.navigatorBar}
                    leftButton={this.renderLeftButton(require('../../assets/imgs/back.png'))}
                    rightButton={this.renderRightButton()}
                />
                {/* {this.state.loading ? <Loading /> : <RecommendTea isRefreshing={this.state.isRefreshing} loadMore={this.loadMore} handleRefresh={this.handleRefresh} TeacherList={this.state.TeacherList} {...this.props} />}
                <BottomBarLimit /> */}

                <ScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.isRefreshing}
                            onRefresh={this._onRefresh.bind(this)}
                            tintColor="#FF8A00"
                            // title="加载中..."
                            titleColor="#ddd"
                            colors={['#FF8A00']}
                            progressBackgroundColor="#ffffff"
                        />
                    }
                    onScroll={this._onScroll.bind(this)}
                    scrollEventThrottle={20}
                >
                    <RecommendTea isRefreshing={this.state.isRefreshing} from={'TeacherSearchpage'} loadMore={this.loadMore} handleRefresh={this.handleRefresh} TeacherList={this.state.TeacherList} reSearchData={()=>this.reSearchData()} {...this.props}  />
                    <View style={styles.loadMore}>
                        {this.state.isLoading&&!this.isRefreshing ? <Text style={styles.loadMoreText}>正在加载中...</Text> : <Text style={styles.loadMoreText}>已经全部加载完毕</Text>}
                    </View>
                </ScrollView>
            </View>
        )
    }

    reSearchData () {
        // alert(1212333)
        cacheData = {
            nextPage: 1,
            total: 0,
            items: []
        }
        this.setState({
            TeacherList: [],
            isRefreshing: false,
            TeacherMore: false
        },()=>{
            // console.log(this.state.TeacherList, 'TeacherList')
            this._fetchData();
        });
        
    }

    componentWillUnmount() {
        // console.log('componentWillUnmount','TeacherList')
        cacheData = {
            nextPage: 1,
            total: 0,
            items: []
        }
        this.setState({
            TeacherList: [],
            isRefreshing: false,
            TeacherMore: false
        });
    }

    _onRefresh = () => {
        cacheData = {
            total: 0,
            items: [],
            nextPage: 1
        }
        this.setState({
            TeacherList: [],
            isRefreshing: true,
            TeacherMore: false,
            isLoading: false
        }, () => {
            this._fetchData();
        })
    }

    _onScroll = (event) => {
        if (this.state.isLoading || !this.hasMoreTeacher()) {
            return;
        }
        let y = event.nativeEvent.contentOffset.y;
        let height = event.nativeEvent.layoutMeasurement.height;
        let contentHeight = event.nativeEvent.contentSize.height;
        if (y + height >= contentHeight - 20) {
            this.setState({
                isLoading: false
            }, () => {
                // global.log(1212121212121212,'request url');
                cacheData.nextPage = cacheData.nextPage + 1;
                global.log(cacheData.nextPage,'----cacheData.nextPage ');
                this._fetchData()
            });

        }
    }

    hasMoreTeacher() {
        if (this.state.TeacherList.length >= cacheData.total && cacheData.total > 0) {
            this.setState({
                TeacherMore: false
            })
            // console.log('false')
            return false
        }
        // console.log('true')

        return true
    }

    renderRightButton(image) {
        return <View
            style={{ padding: 8 }}
        >
            {/* <Image
                style={{ width: 16, height: 14 }}
                source={image} /> */}
            <View style={{ flexDirection: 'row' }}>
                {/* <Icon style={{ fontSize: 16, color: '#666', padding: 3 }} name={'search'} /> */}
                <TouchableOpacity onPress={() => this.handleSearch()} style={{
                    flexDirection
                        : 'row', justifyContent: 'center', alignItems: 'center'}}>
                    <Image
                        style={{ width: 14, height: 14, marginRight: 1 }}
                        source={require('../../assets/imgs/search.png')} />
                    <Text style={{ marginLeft: 2, color: '#666' }}>搜索</Text>
                </TouchableOpacity>
                {/* <TouchableOpacity onPress={() => this.handleSort()} style={{ marginLeft: 10 }}><Icon style={{ fontSize: 16, color: '#666', padding: 3}} name={'sort'} /></TouchableOpacity> */}
            </View>
        </View>;
    }

    handleSearch() {
        // global.log(page);
        var that = this;
        this.props.navigation.navigate('SearchComPage', {
            type: 'teacher',
            refreshPage: function() {
                // alert(121212,'12');
                that.reSearchData();
            }
        })
    }

    handleSort() {
        // global.log(page);
        cacheData = {
            total: 0,
            items: [],
            nextPage: 1
        }

        this.setState({
            TeacherList: [],
            isRefreshing: false,
            TeacherMore: false
        });

        var SORTBYTIME = this.state.SORTBYTIME == '1' ? '0' : '1'
        var data = {
            "USERID": this.state.USERID,
            "SORTBYTIME": SORTBYTIME,
            "NAME": this.state.NAME
        };
        // console.log('sort', data);
        this.setState({
            SORTBYTIME
        }, ()=>{
            this._fetchData();
        });
        
        
    }
}

const styles = StyleSheet.create({
    appContainer: {
        flex: 1,
        // height: 200
    },
    loadMore: {
        flexDirection: 'row',
        justifyContent: 'center',
        height: 50,
        alignItems: 'center',
    },
    loadMoreText: {
        color: '#999',
    }
})